# -*- encoding: utf-8 -*-
import json

from flask import Blueprint, request, g, session

relation_api = Blueprint("relation", __name__, url_prefix="/relation")
from toutiao.model.user import User, relation_jj,UserChannel,Channel,ArticContent,Artice
from toutiao.model.j import db
from toutiao.view.user import login_Re
from toutiao.error_message import ERROR_MESSAGE

@relation_api.route("/follow", methods=("POST", "GET"))
@login_Re
def follow_S():
    user_id = session.get('user_id')  # 发起方
    print(type(user_id))
    if not user_id:
        return {"code": 20002, "message": "麻烦请先登录"}
    ta_user_id = request.form.get('target_user_id')
    target_user = User.query.filter_by(id=ta_user_id).first()
    if not target_user:
        cot= {"code": 20002, "message": "关注用户不存在"}
    # 再判断target_user_id是否存在

    # 1:关注关系
    # GET: 获取所有关注人的信息
    # POST: 发起关注
    # 1、relation里增加或者修改一条数据
    relation = relation_jj.query.filter_by(user_id=user_id, target_user_id=ta_user_id).first()
    if not relation:
        # 加一条
        rela = relation_jj(user_id=user_id, target_user_id=ta_user_id, relation='关注',is_deleted=0)
        db.session.add(rela)
        u = User.query.filter_by(id=user_id).first()
        print(type(u.following_count))
        u.following_count += 1
        # 自增加1
        # 3、user被关注的人的粉丝人数+1
        u = User.query.filter_by(id=ta_user_id).first()

        u.fans_count += 1  # 自增加1
        u.is_deleted = 0
        cot = {'code': 200, 'message': '已关注'}
        # 加入db
    else:
        if relation.relation == '关注':
            relation.relation='未知'
            u = User.query.filter_by(id=user_id).first()
            print(type(u.following_count))
            u.following_count -= 1
            u = User.query.filter_by(id=ta_user_id).first()

            u.fans_count -= 1  # 自增加1
            u.is_deleted=1
            cot={'code': 200, 'message': '取消成功'}
        elif relation.relation == '未知':
            relation.relation='关注'
            u = User.query.filter_by(id=user_id).first()
            print(type(u.following_count))
            u.following_count += 1
            # 自增加1
            # 3、user被关注的人的粉丝人数+1
            u = User.query.filter_by(id=ta_user_id).first()

            u.fans_count += 1  # 自增加1
            u.is_deleted =0
            cot = {'code': 200, 'message': '已关注'}

        # 2、user发起关注的人的关注人数+1
    db.session.commit()
    return cot



@relation_api.route("/channel_follow", methods=("POST", ))
@login_Re
def Channel_follow():
    user_id = session.get('user_id')
    if request.method=='post':


        channel_id = request.form.get('channel_id')
        u=Channel.query.filter_by(id=channel_id).first()
        if not u:
            return {'code': 500, 'msg': '频道不存在'}
        channel = UserChannel.query.filter_by(user_id=user_id, channel_id=channel_id).first()
        if not channel:
            user = UserChannel(user_id=user_id, channel_id=channel_id, is_deleted=0)
            db.session.add(user)
            return {'code': 200, 'msg': '关注成功'}
        else:
            if channel.is_deleted == 1:
                channel.is_deleted = 0
                return {'code': 200, 'msg': '关注成功'}
            elif channel.is_deleted == 0:
                channel.is_deleted = 1
                return{'code': 200, 'msg': '取消成功  '}

        db.session.commit()
    else:
        user_ca=UserChannel.query.filter_by(user_id=user_id,is_deleted=0).all()
        ch=[i.channel_id for i in user_ca]
        
        res=[]
        for channel_id in ch:
            df=Channel.query.filter_by(id=channel_id).first()
            item={
                'channel_id':channel_id,
                'name':df.name,
                'update_tm':df.mtime
            }
            res.append(item)
        return res


@relation_api.route("/Artice_add", methods=("POST", ))
@login_Re
def Artice_add():
    data = json.loads(request.data)
    user_id = session.get('user_id')
    channel_id=data.get('channel_id')
    channel = Channel.query.filter_by(id=channel_id).first()
    if not channel:
        return {'code': 2221, 'msg': ERROR_MESSAGE.get(2221)}
    title = data.get('title')
    if not title:
        return {'code':3001,'msg':ERROR_MESSAGE.get(3331)}
    content=data.get('content')
    try:
        v=Artice(user_id=user_id,channel_id=channel_id,title=title,is_deleted=0)
        db.session.add(v)
        db.session.flush()
        if content:
            a = ArticContent(artist_id=v.id,content=content)
            db.session.add(a)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(str(e))
        return {'code':1001,'msg':"错误"}

    return {'code':200,'msg':'发布成功'}





